﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System.Xml.Linq;
using System.Reflection.Metadata;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using Castle.Core.Resource;
using MailKit.Search;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// 创建WMS物流计划明细
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TMStoWMSAddShipPlanController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_zh;
        public readonly string con_qh;
        public readonly string con_yb;


        public TMStoWMSAddShipPlanController(ILogger<TMtoWMSAddShipPlanRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            con_zh = _configuration.GetConnectionString("WMSDbConnection_ZH");
            con_qh = _configuration.GetConnectionString("WMSDbConnection");
            con_yb = _configuration.GetConnectionString("WMSDbConnection_YB");
            _logger = loggerFactory.CreateLogger<TMStoWMSAddShipPlanController>();
        }

        /// <summary>
        /// 创建WMS物流计划明细
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostTMSAddWMSShipPlan([FromBody] TMtoWMSAddShipPlanRequestDto strparm)
        {
            string strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            TMtoWMSAddShipPlanResponseDto re = new TMtoWMSAddShipPlanResponseDto();
            string w_plan_code = strparm.w_plan_code;
            string in_con = "";//目标WMS数据库
            try
            {
                if (w_plan_code == "")
                {
                    strMsg = "w_plan_code must be not null";
                }
                if (strparm.factory_code == "")
                {
                    strMsg = "w_plan_code must be not null";
                }
                else
                {
                    if (strparm.factory_code.Contains("zh"))
                    {
                        in_con = con_zh;
                    }
                    else
                    {
                        if (strparm.factory_code.Contains("qh"))
                        {
                            in_con = con_qh;
                        }
                        else
                        {
                            if (strparm.factory_code.Contains("sc"))
                            {
                                in_con = con_yb;
                            }
                            else
                            {
                                if (strparm.factory_code.Contains("gz"))
                                {

                                }
                                else
                                {
                                    strMsg = "factory_code=<" + strparm.factory_code + "> not find ";
                                }                                
                            }
                        }
                    }
                }

                if (strMsg == "")
                {

                    if (strparm.factory_code.Contains("gz"))
                    {
                        dic = new Dictionary<string, string>(); //查询公用dic
                        dic.Add("logistics_plan_no", w_plan_code);//查询对应物流计划
                        DataTable so_dt = MethodHelp.GetTableInfo("TMS0060", dic, con);//获取物流计划明细，订单数据源
                        if (so_dt.Rows.Count>0)
                        {
                            WMS_SalesOrderCreateRequestDto data = new WMS_SalesOrderCreateRequestDto();
                            WMS_SalesOrderCreateHeaderDto header = new WMS_SalesOrderCreateHeaderDto();
                            List<WMS_SalesOrderCreateHeader> header_input = new List<WMS_SalesOrderCreateHeader>();
                            foreach (DataRow item in so_dt.Rows)
                            {
                                dic = new Dictionary<string, string>(); //查询公用dic
                                dic.Add("logistics_plan_no", w_plan_code);//查询对应物流计划
                                dic.Add("salesorderno", item["salesorderno"].ToString());//查询对应物流计划
                                DataTable sod_dt = MethodHelp.GetTableInfo("TMS0061", dic, con);//获取物流计划明细，订单数据源
                                if (sod_dt.Rows.Count>0)
                                {
                                    List<WMS_SalesOrderCreate_Details> details_input = new List<WMS_SalesOrderCreate_Details>();
                                    //循环插入明细
                                    foreach (DataRow row in sod_dt.Rows)
                                    {
                                        details_input.Add(new WMS_SalesOrderCreate_Details
                                        {
                                            orderLineNo = DB.ToInt(row["salesorderline"].ToString()),
                                            sku = row["materialcode"].ToString(),
                                            qtyOrdered = DB.ToInt(row["materialamount"].ToString()),
                                            dedi05 = row["salesorderline"].ToString(),
                                            dedi06 = row["ccode"].ToString()
                                        }) ;
                                    }

                                    //添加到header
                                    if (details_input!=null)
                                    {
                                        header_input.Add(new WMS_SalesOrderCreateHeader
                                        {
                                            warehouseId = "H01",
                                            customerId = "H01",
                                            orderType = "GLJY",
                                            soReference1 = item["salesorderno"].ToString(),
                                            soReference2 = item["salesorderno"].ToString(),
                                            soReference3 = item["logistics_plan_no"].ToString(),
                                            consigneeId = item["customer_code"].ToString(),
                                            consigneeName = item["customer_name"].ToString(),
                                            hedi04 = "H01",
                                            hedi05 = "APPROVE",
                                            details = details_input
                                        }) ;
                                    }

                                   
                                }
                                else
                                {
                                    strMsg = "logistics_plan_no=<" + w_plan_code + "> ,订单号=<"+ item["salesorderno"].ToString() + ">找不到对应明细信息!";
                                }
                                                            
                            }

                            if (header_input!=null)
                            {
                                header.header = header_input;
                            }
                            if (header!=null)
                            {
                                data.data = header;
                            }


                            if (data!=null)
                            {
                                Dictionary<string, string> urldic = new Dictionary<string, string>(); //URL获取dic
                                urldic.Add("function_description", "内部:组件WMS_销售订单新增");//查看URL配置表地址描述
                                DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                                if (url_dt.Rows.Count > 0)
                                {
                                    string jsonText = JsonConvert.SerializeObject(data);
                                    var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, "", "否");
                                    WMS_SalesOrderCreateResponseDto psp = JsonConvert.DeserializeObject<WMS_SalesOrderCreateResponseDto>(reAgv);
                                    if (psp.code > 0)
                                    {
                                        strMsg = strMsg + "-" + "CRM ERR:" + psp.message;
                                    }
                                }                                
                            }



                        }
                        else
                        {
                            strMsg = "logistics_plan_no=<" + w_plan_code + "> 找不到对应订单信息!";
                        }
                    }
                    else
                    {
                        dic = new Dictionary<string, string>(); //查询公用dic
                        dic.Add("logistics_plan_no", w_plan_code);//查询对应物流计划
                        DataTable wl_dt = MethodHelp.GetTableInfo("TMS0012", dic, con);//获取物流计划信息
                        if (wl_dt.Rows.Count > 0)
                        {
                            dic = new Dictionary<string, string>(); //查询公用dic
                            dic.Add("w_plan_code", w_plan_code);//查询对应物流计划
                            string SQL = MethodHelp.GetTranSQL("TMS0014", dic, con);//转换删除现有量表SQL语句
                            if (SQL == "")
                            {
                                strMsg = "TMS0014,Parameter conversion failed";
                            }
                            else
                            {
                                strSqlList.Add(SQL.ToString());
                            }
                            foreach (DataRow item in wl_dt.Rows)
                            {
                                string factory_code = item["factory_code"].ToString();
                                string id = item["id"].ToString();
                                string w_create_date = item["w_create_date"].ToString();
                                string w_creator = item["w_creator"].ToString();
                                string p_creator = item["p_creator"].ToString();
                                string w_material_amount = item["w_material_amount"].ToString();
                                string create_date = item["create_date"].ToString();
                                string plan_code = item["plan_code"].ToString();
                                string ship_date = item["ship_date"].ToString();
                                string customer_name = item["customer_name"].ToString();
                                string start_address = item["start_address"].ToString();
                                string target_address = item["target_address"].ToString();
                                string customer_po = item["customer_po"].ToString();
                                string sales_man = item["sales_man"].ToString();
                                string so_type = item["so_type"].ToString();
                                string salesorder_no = item["salesorder_no"].ToString();
                                string material_specifications = item["material_specifications"].ToString();
                                string material_code = item["material_code"].ToString();
                                string material_name = item["material_name"].ToString();
                                string material_resistance = item["material_resistance"].ToString();
                                string p_material_amount = item["p_material_amount"].ToString();
                                string remarks = item["remarks"].ToString();
                                string customer_batch_no = item["customer_batch_no"].ToString();
                                string salesorderline = item["salesorderline"].ToString();


                                if (w_material_amount == "")
                                {
                                    w_material_amount = "0";
                                }

                                if (p_material_amount == "")
                                {
                                    p_material_amount = "0";
                                }

                                dic = new Dictionary<string, string>(); //查询公用dic
                                dic.Add("factory_code", factory_code);//基地
                                dic.Add("id", id);//物流计划行id
                                dic.Add("w_create_date", w_create_date);//物流计划创建日期
                                dic.Add("w_creator", w_creator);//物流计划创建人
                                dic.Add("p_creator", p_creator);//发货计划创建人
                                dic.Add("w_plan_code", w_plan_code);//物流计划单号
                                dic.Add("w_material_amount", w_material_amount);//物流计划数量
                                dic.Add("create_date", create_date);//发货计划创建时间
                                dic.Add("plan_code", plan_code);//发货计划单号
                                dic.Add("ship_date", ship_date);//发货日期
                                dic.Add("customer_name", customer_name);//客户名称
                                dic.Add("start_address", start_address);//发货地址
                                dic.Add("target_address", target_address);//收货地址
                                dic.Add("customer_po", customer_po);//客户PO
                                dic.Add("sales_man", sales_man);//业务员
                                dic.Add("so_type", so_type);//订单类型
                                dic.Add("salesorder_no", salesorder_no);//销售订号
                                dic.Add("material_specifications", material_specifications);//规格型号
                                dic.Add("material_code", material_code);//物料编码
                                dic.Add("material_name", material_name);//产品名称
                                dic.Add("material_resistance", material_resistance);//电阻
                                dic.Add("p_material_amount", p_material_amount);//计划数量
                                dic.Add("remarks", remarks);//备注
                                dic.Add("customer_batch_no", customer_batch_no);//客户批次号
                                dic.Add("salesorderline", salesorderline);//销售订单ID

                                string strSQL = MethodHelp.GetTranSQL("TMS0013", dic, con);//转换删除现有量表SQL语句
                                if (strSQL == "")
                                {
                                    strMsg = "TMS0013,Parameter conversion failed";
                                }
                                else
                                {
                                    strSqlList.Add(strSQL.ToString());
                                }
                            }

                            if (strSqlList.Count > 0)
                            {
                                if (strMsg == "")
                                {
                                    bool A = DB.ExecuteNoQueryTran(strSqlList, in_con);
                                    if (A)
                                    {

                                    }
                                    else
                                    {
                                        strMsg = " Database insert failed";
                                    }
                                }
                            }
                            else
                            {
                                strMsg = "Handle No insertion data present";
                            }

                        }
                        else
                        {
                            strMsg = "logistics_plan_no=<" + w_plan_code + "> info  not find";
                        }
                    }
                                    
                }
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

            if (strMsg == "")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;

            }


            _logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);

        }


    }
}
